import router from './router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { LC_USERTOKEN } from './global/constant'
import CacheService from './utils/cache'
import useAppStore from '@/store/app'
import { matchRoutes } from '@/utils/match-route'

// import { Message } from 'element-ui'
// import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false })

const whiteList = ['/login']

router.beforeEach(async (to, from, next) => {
  NProgress.start()

  // set page title
  // document.title = getPageTitle(to.meta.title)

  const hasToken = CacheService.getItem(LC_USERTOKEN)

  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      const appStore = useAppStore()
      const hasRoles = appStore.userInfo.id && appStore.userMenus.length > 0
      if (hasRoles) {
        if (to.path == '/layout' && appStore.homePagePath) {
          next(appStore.homePagePath)
        } else {
          next()
        }
      } else {
        try {
          await appStore.getUserInfo()
          const accessRoutes = await appStore.getUserMenus()
          matchRoutes(accessRoutes)
          next({ ...to, replace: true })
        } catch (error) {
          // remove token and go to login page to re-login
          appStore.logout()
          // Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})
router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
